package io.renren.service.impl;

import io.renren.common.utils.ConfigConstant;
import io.renren.common.utils.DecimalUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.ProjectConstant;
import io.renren.common.utils.Query;
import io.renren.common.validator.Assert;
import io.renren.dao.TeamDao;
import io.renren.entity.BalanceDetailEntity;
import io.renren.entity.MemberEntity;
import io.renren.entity.TeamCountDto;
import io.renren.entity.TeamEntity;
import io.renren.service.BalanceDetailService;
import io.renren.service.MemberService;
import io.renren.service.SysConfigService;
import io.renren.service.TeamService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

@Service("teamService")
public class TeamServiceImpl extends ServiceImpl<TeamDao, TeamEntity> implements TeamService {

	@Autowired
	MemberService memberService;

	@Autowired
	BalanceDetailService balanceDetailService;

	@Autowired
	SysConfigService sysConfigService;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		Page<TeamEntity> page = this.selectPage(new Query<TeamEntity>(params).getPage(), new EntityWrapper<TeamEntity>());

		return new PageUtils(page);
	}

	@Override
	public TeamCountDto selectAccountingByMemberId(Long memberId, String startDate, String endDate) {
		return baseMapper.selectAccountingByMemberId(memberId, startDate, endDate);
	}

	@Override
	public TeamCountDto countTeam(Long memberId, String startDate, String endDate) {
		return baseMapper.countTeam(memberId, startDate, endDate);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void commission(Long memberId, double amount) {
		TeamEntity teamEntity = this.selectOne(new EntityWrapper<TeamEntity>().eq("member_id", memberId));
		if (teamEntity != null) {
			List<BalanceDetailEntity> details = new ArrayList<BalanceDetailEntity>();
			List<MemberEntity> members = new ArrayList<MemberEntity>();
			Date now = new Date();
			if (teamEntity.getHigherOne() != null) {
				int teamUsers = this.selectCount(new EntityWrapper<TeamEntity>().where("higher_one={0} or higher_two={1} or higher_three={2}", teamEntity.getHigherOne(), teamEntity.getHigherOne(), teamEntity.getHigherOne()));
				if (teamUsers >= sysConfigService.getValueI(ConfigConstant.ENABLE_LEVEL_ONE)) {

					double comm = DecimalUtils.mul(amount, sysConfigService.getValueD(ConfigConstant.REC_LEVEL_ONE));

					if (comm > 0) {

						// 更新余额
						MemberEntity member = memberService.selectById(teamEntity.getHigherOne());
						member.setBalance(DecimalUtils.add(member.getBalance(), comm));
						members.add(member);

						// 插入明细
						BalanceDetailEntity grabDetail = new BalanceDetailEntity();
						grabDetail.setMemberId(member.getId());
						grabDetail.setBalanceChange(comm);
						grabDetail.setType(ProjectConstant.ORDER_TYPE_AGENCY_INCOME);
						grabDetail.setDescription("推荐会员奖励");
						grabDetail.setCreateTime(now);
						details.add(grabDetail);
					}
				}
			}
			if (teamEntity.getHigherTwo() != null) {
				int teamUsers = this.selectCount(new EntityWrapper<TeamEntity>().where("higher_one={0} or higher_two={1} or higher_three={2}", teamEntity.getHigherTwo(), teamEntity.getHigherTwo(), teamEntity.getHigherTwo()));
				if (teamUsers >= sysConfigService.getValueI(ConfigConstant.ENABLE_LEVEL_TWO)) {

					double comm = DecimalUtils.mul(amount, sysConfigService.getValueD(ConfigConstant.REC_LEVEL_TWO));

					if (comm > 0) {

						// 更新余额
						MemberEntity member = memberService.selectById(teamEntity.getHigherTwo());
						member.setBalance(DecimalUtils.add(member.getBalance(), comm));
						members.add(member);

						// 插入明细
						BalanceDetailEntity grabDetail = new BalanceDetailEntity();
						grabDetail.setMemberId(member.getId());
						grabDetail.setBalanceChange(comm);
						grabDetail.setType(ProjectConstant.ORDER_TYPE_AGENCY_INCOME);
						grabDetail.setDescription("推荐会员奖励");
						grabDetail.setCreateTime(now);
						details.add(grabDetail);
					}
				}
			}
			if (teamEntity.getHigherThree() != null) {
				int teamUsers = this.selectCount(new EntityWrapper<TeamEntity>().where("higher_one={0} or higher_two={1} or higher_three={2}", teamEntity.getHigherThree(), teamEntity.getHigherThree(), teamEntity.getHigherThree()));
				if (teamUsers >= sysConfigService.getValueI(ConfigConstant.ENABLE_LEVEL_THREE)) {

					double comm = DecimalUtils.mul(amount, sysConfigService.getValueD(ConfigConstant.REC_LEVEL_THREE));

					if (comm > 0) {

						// 更新余额
						MemberEntity member = memberService.selectById(teamEntity.getHigherThree());
						member.setBalance(DecimalUtils.add(member.getBalance(), comm));
						members.add(member);

						// 插入明细
						BalanceDetailEntity grabDetail = new BalanceDetailEntity();
						grabDetail.setMemberId(member.getId());
						grabDetail.setBalanceChange(comm);
						grabDetail.setType(ProjectConstant.ORDER_TYPE_AGENCY_INCOME);
						grabDetail.setDescription("推荐会员奖励");
						grabDetail.setCreateTime(now);
						details.add(grabDetail);
					}
				}
			}
			if (!members.isEmpty()) {
				Assert.isTrue(memberService.updateBatchById(members), "系统繁忙,请重试");
			}
			if (!details.isEmpty()) {
				balanceDetailService.insertBatch(details);
			}

		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void commissionRoom(Long memberId, double amount) {
		double comm = DecimalUtils.mul(amount, sysConfigService.getValueD(ConfigConstant.ROOM_COMMISSION));

		if (comm > 0) {

			Date now = new Date();
			// 更新余额
			MemberEntity member = memberService.selectById(memberId);
			member.setBalance(DecimalUtils.add(member.getBalance(), comm));
			member.setUpdateTime(now);
			Assert.isTrue(memberService.updateById(member), "系统繁忙,请重试");

			// 插入明细
			BalanceDetailEntity detail = new BalanceDetailEntity();
			detail.setMemberId(member.getId());
			detail.setBalanceChange(comm);
			detail.setType(ProjectConstant.ORDER_TYPE_AGENCY_INCOME);
			detail.setDescription("房间佣金");
			detail.setCreateTime(now);
			balanceDetailService.insert(detail);
		}
	}

	@Override
	public Double teamSendPacket(Long memberId, String startDate, String endDate) {
		return baseMapper.teamSendPacket(memberId, startDate, endDate);
	}
}
